﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using LX.Exceptions;
using S4Store.Controllers;
using S4Store.Service;
using S4Store.Domain;

namespace S4Store
{
    /// <summary>
    /// 当错误时返回类型
    /// </summary>
    public enum ErrorReturnType
    {
        Text,
        NormalJson,
        TreeJson
    }

    public class BaseController : Controller
    {
        protected Administrator CurrentUser { get; set; }

        public AdministratorService AdministratorService { get; set; }
        public AdministratorService AuthService { get; set; }

        
        
        /// <summary>
        /// 返回通用错误JSON
        /// </summary>
        private ErrorReturnType returntype = ErrorReturnType.Text;

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            returntype = ErrorReturnType.Text;
            var name = filterContext.ActionDescriptor.ActionName;
            var type = filterContext.Controller.GetType();
            MethodInfo minfo = null;
            if(filterContext.ActionDescriptor.GetParameters().Count()==0)
            {
                minfo = type.GetMethod(name, new Type[]{});
            }else
            {
                List<Type> ts = new List<Type>();
                foreach(var p in filterContext.ActionDescriptor.GetParameters())
                {
                    ts.Add(p.ParameterType);
                }
                minfo = type.GetMethod(name,ts.ToArray());
            }
            if(minfo.ReturnType==typeof(JsonResult)) 
            {
                returntype = ErrorReturnType.NormalJson;
            }
            if (type != typeof(LoginController))
            {
                using (var t = new Transtion())
                {
                    t.Inject(AuthService);
                    if (!AuthService.IsLogined())
                    {
                        if (returntype == ErrorReturnType.NormalJson)
                        {
                            filterContext.Result = new JsonResult
                                                       {
                                                           Data = new
                                                                      {
                                                                          success = false,
                                                                          errmsg = "请重新登录"
                                                                      }
                                                       };
                            //throw new Exception("请重新登录");
                        }
                        else
                        {
                            filterContext.Result = new ContentResult { Content = "请重新登录" };
                        }
                        return;
                    }
                    CurrentUser = AuthService.GetLoginUser();
                    this.ViewBag.CurrentUser = CurrentUser;
                }
            }
            base.OnActionExecuting(filterContext);
        }

        protected override void OnException(ExceptionContext filterContext)
        {

            var exp = GetRealException(filterContext.Exception);
            if (returntype == ErrorReturnType.NormalJson)
            {
                // 标记异常已处理
                filterContext.ExceptionHandled = true;
                ExcuteNormalJsonException(filterContext, exp);
            }
            else
            {
                base.OnException(filterContext);
            }
        }

        private void ExcuteNormalJsonException(ExceptionContext filterContext, Exception exp)
        {
            filterContext.Result = new JsonResult
            {
                Data = new
                {
                    success = false,
                    errmsg = exp.Message
                }
            };
        }

        private Exception GetRealException(Exception exp)
        {
            if (exp is TargetInvocationException)
            {
                return GetRealException((exp as TargetInvocationException).InnerException);
            }
            else
            {
                return exp;
            }
        }

        protected void CheckPower(params Position[] pos)
        {
            bool havapower = false;
            foreach (var p in pos)
            {
                if (this.CurrentUser.Position == p)
                {
                    havapower = true;
                    break;
                }
            }
            if (!havapower)
            {
                throw new Exception("没有执行此操作的权限");
            }
        }

        
    }
}